package com.jf3q.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class SaltPassUtils {
    public static void main(String[] args) {
        String password = "123456"; // 用户输入的密码  明文

        // 生成盐
        byte[] salt = generateSalt();//盐

        // 将密码和盐拼接在一起
        String hashedPassword = hashPassword(password, salt);//密文


        //KzPUxI2xNzkkpn9RILjvfcILlDPxZ8w+LI5l6j1q+20=
        //FXzeQ0LZPH2ZqQ9e3yiPLUC0bULMzak166jbzL1Zp5A=
        System.out.println("Salt: " + Base64.getEncoder().encodeToString(salt));
        System.out.println("Hashed Password: " + hashedPassword);
    }

    //校验密码
    public static Boolean PasswordValidation (String salt,String inputPass,String secretPass ) {

        // 将用户输入的密码与盐值进行相同的加密处理
        String hashedInputPassword = hashPassword(inputPass, Base64.getDecoder().decode(salt));

        // 将加密后的密码与数据库中存储的哈希密码进行比较
        if (hashedInputPassword.equals(secretPass)) {

            return true;
        } else {
            return false;
        }
    }

    // 生成盐的方法
    public static byte[] generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return salt;
    }

    // 对密码进行加盐加密的方法
    public static String hashPassword(String password, byte[] salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(salt);
            byte[] hashedPassword = md.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(hashedPassword);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
